package server.forms;

import javax.servlet.http.HttpServletRequest;

import commons.User;

/**
 * Class used to connect an user
 * @author Romain Pellerin
 */
public final class ConnectionForm {

	private String nickname;
	private User user;
	private String error;
	
	/**
	 * Check wheter a given password correspond to a valid user or not.
	 * @param request The HTTP request, containing a request value called 'password'
	 * @throws ConnectionFormException If something wrong happened
	 */
	public void connectUser(HttpServletRequest request) {
		String pwd = getRequestValue(request, "password");
		this.nickname = getRequestValue(request, "nickname");
		try {
			user = new User(nickname, User.sayTrueIfThisIsTheAdminPasswordOrFalseIfThisIsTheGuestPasswordOrExceptionIfItIsArandomString(pwd));
		} catch (Exception e) {
			error = e.getMessage();
		}
	}
	
	/**
	 * Get the error if there is
	 * @return The error or null if there is none.
	 */
	public String getError() {
		return error;
	}

	/**
	 * Get the nickname of the user connected
	 * @return The user's nickname. May be null.
	 */
	public String getNickname() {
		return this.nickname;
	}
	
	/**
	 * Get the user connected
	 * @return The user connected. May be null.
	 */
	public User getUser() {
		return this.user;
	}
	
	/**
	 * Method used to retriveve a specific value from an HTTP request
	 * @param request The HTTP request
	 * @param fieldName The fieldname searched
	 * @return The value found, or null if <code>fieldName</code> isn't existing
	 */
	private static String getRequestValue(HttpServletRequest request, String fieldName) {
		String val = request.getParameter(fieldName);
		if (val == null || val.trim().length() == 0) {
			return null;
		} else {
			return val;
		}
	}
}
